package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DispatchJobHandler {

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @Autowired
    private SearchFeignClient searchFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //  编写执行器要完成的任务！

    /**
     *  更新最近播放排行榜
     * @return
     */
    @XxlJob("updateLatelyAlbumRankingJob")
    public Result updateLatelyAlbumRankingJob() {
        log.info("执行器执行任务！");
        //  创建日志对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        long startTime = System.currentTimeMillis();
        try {
            //  远程调用更新排行榜的方法！
            searchFeignClient.updateLatelyAlbumRanking();
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(e.getMessage());
        }
        //  获取结束时间
        long endTime = System.currentTimeMillis();
        xxlJobLog.setTimes((int) (endTime-startTime));
        //  保存对象数据
        xxlJobLogMapper.insert(xxlJobLog);
        //  返回
        return Result.ok();
    }

    /**
     * 更新用户vip状态
     * @return
     */
    @XxlJob("updateVipExpireStatus")
    public Result updateVipExpireStatusJob() {
        log.info("执行器执行任务！");
        //  创建日志对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        long startTime = System.currentTimeMillis();
        try {
            //  远程调用更新用户vip状态的方法！
            userInfoFeignClient.updateVipExpireStatus();
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(e.getMessage());
        }
        //  获取结束时间
        long endTime = System.currentTimeMillis();
        xxlJobLog.setTimes((int) (endTime-startTime));
        //  保存对象数据
        xxlJobLogMapper.insert(xxlJobLog);
        //  返回
        return Result.ok();
    }



}